import json
import logging

from diyLLM.GetParamTest import response
from utils.expand import *
import requests
from config.config import *
from flask import jsonify

@timecost
def dify_chat_api(query, inputs, apikey):
    invoke_user = Config.DIFY_INVOKE_USER

    data = {
        'query': query,
        'inputs': inputs,
        'response_mode': 'blocking',
        'user': invoke_user,
        'files': [],
        'auto_generate_name': 'false'
    }

    logging.error('dify request data：%s', json.dumps(data, ensure_ascii=False))
    response = request_dify('/chat-messages', data, apikey)
    logging.error('dify response：%s', json.dumps(response, ensure_ascii=False))

    if 'answer' in response:
        return {
            'status': 200,
            'data': json.loads(response['answer']),
        }
    else:
        return {
            'status': 500
        }

# 请求dify
def request_dify(url:str, data: json, apikey:str):
    request_url = Config.DIFY_BASE_URL + url
    headers = {
        'User-Agent': 'PostmanRuntime/7.29.0',
        'Authorization': 'Bearer ' + apikey,
        'Content-Type': 'application/json'
    }
    response = requests.post(request_url, json=data, headers=headers).json()
    return response

